import Header from '@/components/header';
import styles from "./index.module.scss";
import MenuBar from './components/menuBar';
import MainEdit from './components/MainEdit';
import Results from './components/Results';
import History from './components/History';
import LayerHistory from './components/LayerHistory';
import ImageGallery from './components/ImageGallery';
import { useState, useRef, useMemo, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { updateCurrentImageByMenuKey, selectCurrentImage, selectLayerImages, reorderLayerImages } from '@/store/slices/imageEditSlice';
import sharedWebSocket from '@/services/sharedWebSocket';


export default function ImageEditPage() {
  const dispatch = useDispatch();
  const currentImage = useSelector(selectCurrentImage);
  const layerImages = useSelector(selectLayerImages);
  const [currentMenuKey, setCurrentMenuKey] = useState('text');
  const [currentMenuTitle, setCurrentMenuTitle] = useState('文生图');
  const [showMainEdit, setShowMainEdit] = useState(true);
  const [showResults, setShowResults] = useState(true);
  const [showHistory, setShowHistory] = useState(true);
  const [showBottom, setShowBottom] = useState(false);
  const [showLayerHistory, setShowLayerHistory] = useState(false);
  const [selectedTool, setSelectedTool] = useState(null); // 默认选择点选工具
  const [toolSize, setToolSize] = useState(20); // 工具大小
  const [selectedRatio, setSelectedRatio] = useState('16:9'); // 画幅比例
  const [selectedImageKey, setSelectedImageKey] = useState(null); // 当前选中的图层key
  
  // 监听layerImages变化，只在没有选中状态时自动选中第一张图片
  useEffect(() => {
    if (currentMenuKey === 'layer' && layerImages.length > 0 && !selectedImageKey) {
      // 默认选中第一个图层（最新上传的）
      const firstImageUrl = layerImages[layerImages.length - 1];
      const firstImageKey = `layer-${firstImageUrl.id}`;
      setSelectedImageKey(firstImageKey);
      
      // 通知Results组件选中了哪张图片
      if (resultsContainerRef.current?.setSelectedImage) {
        resultsContainerRef.current.setSelectedImage(firstImageKey);
      }
      
      // 延迟执行高亮显示，确保DOM已渲染
      setTimeout(() => {
        const imageElement = document.querySelector(`[data-key="${firstImageKey}"]`);
        if (imageElement) {
          // 移除其他图片的选中状态
          document.querySelectorAll('[data-key^="layer-"]').forEach(img => {
            img.parentElement.style.outline = 'none';
            img.parentElement.style.outlineOffset = '0px';
          });
          
          // 为选中的图片添加高亮效果
          imageElement.parentElement.style.outline = '3px solid #1890ff';
          imageElement.parentElement.style.outlineOffset = '-3px';
        }
      }, 100);
    }
  }, [layerImages, currentMenuKey, selectedImageKey]);
  
  // 跟踪画布数据状态
  const [selectedPoints, setSelectedPoints] = useState([]);
  const [selectGreenPoints, setSelectGreenPoints] = useState([]);
  const [selectionRects, setSelectionRects] = useState([]);
  const [brushStrokes, setBrushStrokes] = useState([]);
  const [erasureText, setErasureText] = useState(''); // segmentation工具的文本输入
  
  const handleToolChange = (toolKey) => {
    // 如果点击的是当前已选中的工具，则取消选中
    if (selectedTool === toolKey) {
      setSelectedTool(null); // 取消选中，此时可以拖动图片
      return;
    }
    
    setSelectedTool(toolKey);
    // 切换工具时清空相关数据状态
    setSelectedPoints([]);
    setSelectGreenPoints([]);
    setSelectionRects([]);
    setBrushStrokes([]);
    setErasureText(''); // 清空文本输入
    // 清空画布内容
    if (resultsContainerRef.current?.clearCanvas) {
      resultsContainerRef.current.clearCanvas();
    }
  };

  useEffect(() => {
    // 切换工具时清空相关数据状态
    setSelectedPoints([]);
    setSelectGreenPoints([]);
    setSelectionRects([]);
    setBrushStrokes([]);
    setErasureText(''); // 清空文本输入
    // 清空画布内容
    if (resultsContainerRef.current?.clearCanvas) {
      resultsContainerRef.current.clearCanvas();
    }
  }, [selectedRatio]);
  
  const handleToolSizeChange = (size) => {
    setToolSize(size);
  };
  
  // 处理点选变化
  const handlePointSelectionChange = (points) => {
    console.log('选中的点(原图坐标):', points);
    setSelectedPoints(points);
  };

  // 处理绿色点变化
  const handleGreenPointSelectionChange = (points) => {
    console.log('绿色点(原图坐标):', points);
    setSelectGreenPoints(points);
  };
  
  // 处理框选变化
  const handleRectSelectionChange = (rects) => {
    console.log('框选区域(原图坐标):', rects);
    setSelectionRects(rects);
  };
  
  // 处理画笔笔触变化
  const handleBrushStrokesChange = (strokes) => {
    setBrushStrokes(strokes);
  };
  
  // 判断是否有数据可以提交
  const hasDataToSubmit = useMemo(() => {
    // 必须有图片上传成功且有操作数据才能提交
    const hasImage = currentImage||layerImages.length;
    const hasOperationData = selectedPoints.length > 0 || selectionRects.length > 0 || brushStrokes.length > 0;
    const hasSegmentationText = selectedTool === 'segmentation' && erasureText.trim() !== '';
    return hasImage && (hasOperationData || hasSegmentationText);
  }, [currentImage, selectedPoints, selectionRects, brushStrokes, selectedTool, erasureText]);
  
  const handleMenuClick = (item, confirmCallback) => {
    // 更新当前选中的菜单
    setCurrentMenuKey(item.key);
    setCurrentMenuTitle(item.title);
    setSelectedTool(null);
    // 清空选中状态
    setSelectedImageKey(null);
    // 根据菜单键更新当前显示的图片
    dispatch(updateCurrentImageByMenuKey({ menuKey: item.key }));
    // 清空画布内容
    if (resultsContainerRef.current?.clearCanvas) {
      resultsContainerRef.current.clearCanvas();
    }
    
    // 重置所有数据状态
    setSelectedPoints([]);
    setSelectionRects([]);
    setBrushStrokes([]);
    
    // 根据菜单切换显示不同的组件
    if (item.key === 'layer') {
      setShowLayerHistory(true);
      setShowHistory(false);
      // 切换到layer模式时重置选中状态，触发自动选中第一张图片
      setSelectedImageKey(null);
    } else {
      setShowLayerHistory(false);
      setShowHistory(true);
      setSelectedImageKey(null); // 非layer模式也重置选中状态
    }
    
    // 更新组件显示状态
    setShowMainEdit(item.showMainEdit || false);
    setShowResults(item.showResults || false);
    setShowBottom(item.showBottom || false);
    setShowHistory(item.showHistory || false);
    setShowLayerHistory(item.showLayerHistory || false);
    // 调用回调更新菜单状态
    confirmCallback?.();
  };

  const [typeValue, setTypeValue] = useState(1);
  const handleTypeChange = (e) => {
    const newValue = e.target.value ? e.target.value : 1;
    setTypeValue(newValue);
  };

  const [proportion, setProportion] = useState('16:9');
  const [qualityValue, setQualityValue] = useState('1K');
  const [quantityValue, setQuantityValue] = useState(1);
  
  // 创建refs数组来引用每个resultsItem和results容器
  const resultsItemRefs = useRef([]);
  const resultsContainerRef = useRef(null);
  
  // 点击LayerHistory中的图片时设置选中状态并启用拖动
  const handleLayerImageClick = (index) => {
    // LayerHistory组件传递的是originalIndex，直接使用即可
    const actualIndex = index;
    const imageUrl = layerImages[actualIndex];
    const currentSelectedImageKey = `layer-${imageUrl.id}`;
    
    // 更新选中状态
    setSelectedImageKey(currentSelectedImageKey);
    
    // 通知Results组件选中了哪张图片
    if (resultsContainerRef.current?.setSelectedImage) {
      resultsContainerRef.current.setSelectedImage(currentSelectedImageKey);
    }
    
    // 高亮显示选中的图片
    const imageElement = document.querySelector(`[data-key="${currentSelectedImageKey}"]`);
    if (imageElement) {
      // 移除其他图片的选中状态
      document.querySelectorAll('[data-key^="layer-"]').forEach(img => {
        img.parentElement.style.outline = 'none';
        img.parentElement.style.outlineOffset = '0px';
      });
      
      // 为选中的图片添加高亮效果
      imageElement.parentElement.style.outline = '3px solid #1890ff';
      imageElement.parentElement.style.outlineOffset = '-3px';
    }
  };

  // 点击History中的图片时滚动到对应位置
  const handleHistoryImageScroll = (index) => {
    const targetItem = resultsItemRefs.current[index];
    if (targetItem && targetItem.scrollIntoView) {
      targetItem.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest'
      });
    }
  };

  // 处理合成按钮点击
  const handleCompositeClick = () => {
    if (resultsContainerRef.current?.handleDownloadResizedImage) {
      resultsContainerRef.current.handleDownloadResizedImage();
    } else {
      console.error('CanvasDrawing组件的handleDownloadResizedImage方法不可用');
    }
  };

  // 处理图层重排序
  const handleReorderImages = (fromIndex, toIndex) => {
    dispatch(reorderLayerImages({ fromIndex, toIndex }));
  };

  // WebSocket消息监听
  useEffect(() => {
    const handleWebSocketMessage = ({data}) => {
      if (data.func === 'partition_select_success' && data.imageUrl) {
        // 更新当前图片为WebSocket返回的新图片
         dispatch(updateCurrentImageByMenuKey({ menuKey: currentMenuKey, imageUrl: data.imageUrl }));
        console.log('收到分割成功消息，更新图片:', data.imageUrl);
      }
    };

    // 添加WebSocket消息监听器
    sharedWebSocket.on('resp', handleWebSocketMessage);

    // 清理函数
    return () => {
      sharedWebSocket.off('resp', handleWebSocketMessage);
    };
  }, []);
  
  // 监听layerImages变化，设置默认选中状态
  useEffect(() => {
    if (currentMenuKey === 'layer' && layerImages.length > 0) {
      // 默认选中第一个图层（最新上传的）
      const firstImageUrl = layerImages[layerImages.length - 1];
      const defaultSelectedKey = `layer-${firstImageUrl.id}`;
      setSelectedImageKey(defaultSelectedKey);
      
      // 通知Results组件选中了哪张图片
      if (resultsContainerRef.current?.setSelectedImage) {
        resultsContainerRef.current.setSelectedImage(defaultSelectedKey);
      }
      // 高亮显示选中的图片
      const imageElement = document.querySelector(`[data-key="${defaultSelectedKey}"]`);
      if (imageElement) {
        // 移除其他图片的选中状态
        document.querySelectorAll('[data-key^="layer-"]').forEach(img => {
          img.parentElement.style.outline = 'none';
          img.parentElement.style.outlineOffset = '0px';
        });
        
        // 为选中的图片添加高亮效果
        imageElement.parentElement.style.outline = '3px solid #1890ff';
        imageElement.parentElement.style.outlineOffset = '-3px';
      }
    }
  }, [layerImages, currentMenuKey]);
  
  return (
    <div className={styles.imageEditPage} id='imageEditPage'>
      <Header showLogo={false} title="图像工作台" />
      <div className={styles.mainSection}>
        <div className={styles.mainContent}>
          <MenuBar onMenuChange={handleMenuClick}/>
          <MainEdit
            currentMenuKey={currentMenuKey}
            currentMenuTitle={currentMenuTitle}
            typeValue={typeValue}
            onTypeChange={handleTypeChange}
            proportion={proportion}
            setProportion={setProportion}
            qualityValue={qualityValue}
            setQualityValue={setQualityValue}
            quantityValue={quantityValue}
            setQuantityValue={setQuantityValue}
            selectedTool={selectedTool}
            onToolChange={handleToolChange}
            toolSize={toolSize}
            onToolSizeChange={handleToolSizeChange}
            selectedRatio={selectedRatio}
            setSelectedRatio={setSelectedRatio}
            hasDataToSubmit={hasDataToSubmit}
            selectedPoints={selectedPoints}
            selectGreenPoints={selectGreenPoints}
            selectionRects={selectionRects}
            brushStrokes={brushStrokes}
            currentImageUrl={currentImage}
            canvasDrawingRef={resultsContainerRef}
            erasureText={erasureText}
            setErasureText={setErasureText}
            showMainEdit={showMainEdit}
          />
          {showResults && (
            <div className={styles.resultsSection}>
              <Results
                currentMenuKey={currentMenuKey}
                currentMenuTitle={currentMenuTitle}
                ref={resultsContainerRef}
                resultsItemRefs={resultsItemRefs}
                selectedTool={selectedTool}
                toolSize={toolSize}
                selectedRatio={selectedRatio}
                onPointSelectionChange={handlePointSelectionChange}
                onGreenPointSelectionChange={handleGreenPointSelectionChange}
                onBrushStrokesChange={handleBrushStrokesChange}
                onRectSelectionChange={handleRectSelectionChange}
              />
              {showBottom && (
                <ImageGallery />
              )}
            </div>
          )}
          {showHistory && (
            <History onHistoryImageClick={handleHistoryImageScroll} />
          )}
          {showLayerHistory&&(
            <LayerHistory 
                onLayerImageClick={handleLayerImageClick}
              onCompositeClick={handleCompositeClick} 
              layerImages={layerImages}
              onReorderImages={handleReorderImages}
              selectedImageKey={selectedImageKey}
            />
          )}
        </div>
      </div>
    </div>
  );
}
